import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import {
    Message,
    Notification,
    MessageBox
} from "element-ui";

Vue.use(Vuex);

const store = new Vuex.Store({
    // 定义状态
    state: {
        ajaxApi: "/",
        wsApi: "ws://" + location.host + ":" + location.port + "/",
        htApi: "http://" + location.host + ":" + location.port + "/",
        // ajaxApi: 'http://192.168.1.150:9000/',
        // wsApi: 'ws://192.168.1.150:9000/',
        env: process.env.NODE_ENV,
        baseUrl: process.env.BASE_URL,
    },
    actions: {
        // 封装一个 ajax 方法
        ajax(context, {
            url,
            data,
            method,
            succeed
        }) {
            if (url.substr(0, 6) == "local:") {
                url = (context.state.env === "production" ? "./" : "") + url.substr(6);
            } else if (url.substr(0, 5) == "http:") {
                url;
            } else {
                url = context.state.ajaxApi + url;
            }

            axios({
                    url: url,
                    method: method || "get",
                    params: (method || "get") == "get" ? data : {},
                    headers: {
                        token: sessionStorage.token
                    },
                    data: data || {},
                })
                .then(function (res) {
                    if (res.data.code && res.data.code.toString() !== "200") {
                        Message({
                            type: "warning",
                            showClose: true,
                            message: res.data.message,
                        });
                        return false;
                    }

                    if (succeed && typeof succeed == "function") {
                        succeed(res.data);
                    }
                })
                .catch((error) => {
                    console.log(error);

                    if (error.response) {
                        const status = error.response.status;
                        if (status === 401) {
                            window.location.href =
                                context.state.env === "production" ? "./#/login" : "/#/login";
                        } else if (status === 402) {
                            const h = this._vm.$createElement;
                            Notification({
                                title: "授权提醒",
                                duration: 0,
                                dangerouslyUseHTMLString: true,
                                message: h("span", null, [
                                    h("span", null, "授权已过期，请重新"),
                                    h(
                                        "a", {
                                            style: "color: #3579f8",
                                            attrs: {
                                                href: "javascript:;"
                                            },
                                            on: {
                                                click: this._actions.authImport
                                            },
                                        },
                                        "导入授权"
                                    ),
                                ]),
                            });
                        }
                    } else {
                        Message({
                            type: "error",
                            showClose: true,
                            message: "请求失败",
                        });
                    }
                });
        },

        ajaxEx(context, {
            url,
            data,
            method,
            succeed,
            err
        }) {
            if (url.substr(0, 6) == "local:") {
                url = (context.state.env === "production" ? "./" : "") + url.substr(6);
            } else if (url.substr(0, 5) == "http:") {
                url;
            }
            // else 
            // if (context.state.env === "production") {
            //     url;
            // }
            else {
                url = context.state.ajaxApi + url;
            }

            axios({
                    url: url,
                    method: method || "get",
                    params: (method || "get") == "get" ? data : {},
                    headers: {
                        token: sessionStorage.token
                    },
                    data: data || {},
                })
                .then(function (res) {
                    if (res.data.code && res.data.code.toString() !== "200") {
                        Message({
                            type: "warning",
                            showClose: true,
                            message: res.data.message,
                        });
                        return false;
                    }

                    if (succeed && typeof succeed == "function") {
                        succeed(res);
                    }
                })
                .catch((error) => {
                    console.log(error);

                    if (error.response) {
                        const status = error.response.status;
                        if (status === 401) {
                            window.location.href =
                                context.state.env === "production" ? "./#/login" : "/#/login";
                        } else if (status === 402) {
                            const h = this._vm.$createElement;
                            Notification({
                                title: "授权提醒",
                                duration: 0,
                                dangerouslyUseHTMLString: true,
                                message: h("span", null, [
                                    h("span", null, "授权已过期，请重新"),
                                    h(
                                        "a", {
                                            style: "color: #3579f8",
                                            attrs: {
                                                href: "javascript:;"
                                            },
                                            on: {
                                                click: this._actions.authImport
                                            },
                                        },
                                        "导入授权"
                                    ),
                                ]),
                            });
                        }
                    } else {
                        Message({
                            type: "error",
                            showClose: true,
                            message: "请求失败",
                        });
                    }
                });
        },
        // 封装一个 ajax 方法---Service
        ajaxService(context, {
            url,
            data,
            method,
            succeed
        }) {
            if (context.state.env === 'production') {
                url;
            } else {
                url;
            }
            axios({
                url: url,
                method: method || 'get',
                params: (method || 'get') == 'get' ? data : {},
                headers: {
                    'token': sessionStorage.token
                },
                data: data || {}
            }).then(function (res) {
                if (res.data.code && res.data.code.toString() !== '200') {
                    Message({
                        type: 'warning',
                        showClose: true,
                        message: res.data.message,
                    });
                    return false;
                }

                if (succeed && typeof succeed == 'function') {
                    succeed(res.data);
                }
            }).catch((error) => {
                console.log(error.response);
                if (error.response) {
                    const status = error.response.status;
                    if (status === 401) {
                        window.location.href = context.state.env === 'production' ? './#/login' : '/#/login';
                    } else if (status === 402) {
                        const h = this._vm.$createElement;
                        Notification({
                            title: '授权提醒',
                            duration: 0,
                            dangerouslyUseHTMLString: true,
                            message: h('span', null, [
                                h('span', null, '授权已过期，请重新'),
                                h('a', {
                                    style: 'color: #3579f8',
                                    attrs: {
                                        href: 'javascript:;'
                                    },
                                    on: {
                                        click: this._actions.authImport
                                    }
                                }, '导入授权')
                            ])
                        });
                    }
                } else {
                    Message({
                        type: 'error',
                        showClose: true,
                        message: '请求失败'
                    });
                }
            });
        },

        authImport() {
            const h = this._vm.$createElement;
            MessageBox({
                title: "导入授权",
                dangerouslyUseHTMLString: true,
                message: h(
                    "textarea", {
                        style: "width: 100%; height: 100px;",
                        attrs: {
                            id: "authStr"
                        }
                    },
                    ""
                ),
                showCancelButton: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            }).then(() => {
                const authStr = document.getElementById("authStr");
                this.dispatch("ajax", {
                    url: "api/auther",
                    method: "post",
                    data: {
                        content: authStr.value
                    },
                    succeed: () => {
                        Message({
                            type: "success",
                            message: "授权导入成功",
                        });
                        window.location.reload();
                    },
                });
            });
        },
    },
});

export default store;